package com.xncoding.websocket;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.util.*;

/**
 * @Author: LiuLei
 * @Description: 解析api-docs生成ts文件
 * @Date: 2023/7/14  9:53
 * @Version: 1.0
 */
public class JsApiDocs {


    /**
     * 生成方法
     *
     * @param url
     * @param path
     */
    public static void inlet(String url, String path) {
        String s = HttpUtil.get("http://127.0.0.1:18191/ebank/v2/api-docs");
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONObject paths = jsonObject.getJSONObject("paths");
        Set<String> keys = paths.keySet();
        for (String key : keys) {
//            String[] split = key.split("/");
            //文件夹名字
//            String folderName = split[1];
            //文件名字
//            String fileName = split[4];
            //文件路径
//            String filePath = path + "/" + folderName + "/" + fileName + ".ts";
            String data = getData(key, paths);
//            createFile(filePath, data);
        }
    }

    /**
     * 拼接接口数据
     *
     * @param key
     * @param paths
     * @return
     */
    private static String getData(String key, JSONObject paths) {
        String[] split = key.split("/");
        JSONObject jsonObject = paths.getJSONObject(key);
        StringBuilder sb = new StringBuilder();
        //接口类型
        String method = "";
        JSONObject info = null;
        //获取接口数据
        String[] types = {"get", "put", "post", "delete"};
        for (String type : types) {
            info = jsonObject.getJSONObject(type);
            if (info != null) {
                method = type;
                break;
            }
        }
        if (info != null) {
            String summary = info.getString("summary");
            JSONArray parameters = info.getJSONArray("parameters");
            //传入参数
            String param = "";
            //拼在路径？后面的参数
            String query = "";
            String body = "";
            if (parameters != null) {
                Boolean isSize = false;
                Boolean isCurrent = false;
                List<JSONObject> list = JSONArray.parseArray(parameters.toJSONString(), JSONObject.class);
                for (JSONObject json : list) {
                    String in = json.getString("in");
                    String name = json.getString("name");
                    if ("body".equals(in)) {
                        name = "data";
                        body = "\t\tdata\n";
                    }
                    if ("query".equals(in)) {
                        query += "\t\t\t" + name + ": " + name + ",\n";
                    }
                    if("size".equals(name)){
                        isSize = true;
                    } else if("current".equals(name)){
                        isCurrent = true;
                    }else{
                        if (!"".equals(param)) {
                            param += ", ";
                        }
                        param += name;
                    }
                }
                if(isSize){
                    param += ", size";
                }
                if(isCurrent){
                    param += ", current";
                }
            }
            sb.append("// ").append(summary).append("\n");
            sb.append("export function ").append(split[5]).append("(").append(param).append(")").append(" {\n");
            sb.append("\treturn request({\n");
            String replace = key.replace("/{size}/{current}", "/${size}/${current}");
            sb.append("\t\turl: `").append(replace).append("`,\n");
            sb.append("\t\tmethod: '").append(method).append("',\n");
            if (!"".equals(query)) {
                sb.append("\t\tparams: {\n");
                sb.append(query);
                sb.append("\t\t},\n");
            }
            if (!"".equals(body)) {
                sb.append(body);
            }
            sb.append("\t})\n");
            sb.append("}\n");
            return sb.toString();
        }
        return "";
    }

    /**
     * 写入数据到文件
     *
     * @param fileOut 文件路径
     * @param data    写入内容
     * @return
     */
    public static String createFile(String fileOut, String data) {
        //创建文件夹
        File file = new File(fileOut.substring(0, fileOut.lastIndexOf("/")));
        if (!file.exists()) {
            file.mkdirs();
        }
        boolean exists = new File(fileOut).exists();
        FileWriter fileWriter = null;
        try {
            //输出文件
            fileWriter = new FileWriter(fileOut, true);
            //文件不存在
            if (!exists) {
                fileWriter.write("import request from '../request'\n");
                fileWriter.write("\n");
            }
            fileWriter.write(data);
            fileWriter.write("\n");
        } catch (IOException e) {
            return "创建数据文件失败--->" + e.toString();
        } finally {
            try {
                if (fileWriter != null) {
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "OK";
    }

    public static void main(String[] args) {
        inlet("http://192.168.31.133:10315/v2/api-docs?group=ALL", "D:/test");
    }
}
